import java.util.HashMap;
import java.util.Map;

/*
 * @lc app=leetcode.cn id=13 lang=java
 *
 * [13] 罗马数字转整数
 */

// @lc code=start
class Solution {

    /**
     * 3999/3999 cases passed (2 ms)
    Your runtime beats 100 % of java submissions
    Your memory usage beats 68.66 % of java submissions (41.6 MB)
     */
    private int getValue(char ch) {
        switch (ch) {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
            default:
                return 0;
        }
    }

    public int romanToInt(String s) {
        int temp;
        int last = 0, result = 0;
        int len = s.length();
        for (int i = len - 1; i >= 0; i--) {
            temp = getValue(s.charAt(i));
            if (temp < last) {
                result -= temp;
            } else {
                result += temp;
            }
            last = temp;
        }
        return result;
    }

    /**
     * 3999/3999 cases passed (4 ms)
    Your runtime beats 58.07 % of java submissions
    Your memory usage beats 5.03 % of java submissions (42.3 MB)
     */
    public int romanToInt2(String s) {
        Map<Character, Integer> roman = new HashMap(16);
        roman.put('I', 1);
        roman.put('V', 5);
        roman.put('X', 10);
        roman.put('L', 50);
        roman.put('C', 100);
        roman.put('D', 500);
        roman.put('M', 1000);

        int temp;
        int last = 0, result = 0;
        int len = s.length();
        for (int i = len - 1; i >= 0; i--) {
            temp = roman.get(s.charAt(i));
            if (temp < last) {
                result -= temp;
            } else {
                result += temp;
            }
            last = temp;
        }
        return result;
    }
}
// @lc code=end
